﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CompanyManagement.Models
{
    public class CompanyTypeDAO
    {
        CompanyEntities db;

        public CompanyTypeDAO()
        {
            db = new CompanyEntities();
        }

        public List<CompanyType> GetCompanyTypes()
        {
            return db.CompanyTypes.Where(p=>p.IsActive == true).ToList();
        }

        internal bool Insert(CompanyType insertObj)
        {
            try
            {
                db.CompanyTypes.Add(insertObj);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        internal bool Update(CompanyType updateObj)
        {
            try
            {
                var existed = db.CompanyTypes.FirstOrDefault(p => p.ID == updateObj.ID && p.IsActive == true);
                if (existed != null)
                {
                    existed.Name = updateObj.Name;
                    existed.Description = updateObj.Description;

                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        internal bool Delete(CompanyType deleteObj)
        {
            try 
	        {	        
		        var existed = db.CompanyTypes.FirstOrDefault(p=>p.ID == deleteObj.ID && p.IsActive == true);
                if (existed != null)
                {
                    existed.IsActive = false;
                    db.SaveChanges();
                    return true;
                }
                return false;
	        }
	        catch (Exception)
	        {
		        throw;
	        }
        }

        internal bool CheckCompanyTypeInUse(CompanyType deleteObj)
        {
            var companyType = db.CompanyTypes.FirstOrDefault(p => p.ID == deleteObj.ID && p.IsActive == true);
            if (companyType != null)
            {
                return db.Companies.Any(p => p.CompanyTypeCode.Equals(companyType.Code) && p.IsActive == true);
            }
            return false;
        }

        internal bool CheckCompanyTypeExisted(CompanyType insertObj)
        {
            return db.CompanyTypes.Any(p => p.ID != insertObj.ID && p.IsActive == true &&( p.Code.Equals(insertObj.Code) || p.Name.Equals(insertObj.Name)));
        }

        internal CompanyType GetCompanyTypeByID(int companyTypeID)
        {
            return db.CompanyTypes.FirstOrDefault(p=>p.ID == companyTypeID);
        }
    }
}